package com.wyd.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.server.reactive.ServerHttpRequest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;

public class IpUtil {

    // 多次反向代理后会有多个ip值 的分割符
    private final static String IP_UTILS_FLAG = ",";
    // 未知IP
    private final static String UNKNOWN = "unknown";
    // 本地 IP
    private final static String LOCALHOST_IP = "0:0:0:0:0:0:0:1";
    private final static String LOCALHOST_IP1 = "127.0.0.1";

	public static String getIpAddr(ServerHttpRequest request) {
        // 根据 HttpHeaders 获取 请求 IP地址
        String ip = request.getHeaders().getFirst("X-Forwarded-For");
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("x-forwarded-for");
            if (ip != null && ip.length() != 0 && !UNKNOWN.equalsIgnoreCase(ip)) {
                // 多次反向代理后会有多个ip值，第一个ip才是真实ip
                if (ip.contains(IP_UTILS_FLAG)) {
                    ip = ip.split(IP_UTILS_FLAG)[0];
                }
            }
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("X-Real-IP");
        }
        //兼容k8s集群获取ip
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddress().getAddress().getHostAddress();
            if (LOCALHOST_IP1.equalsIgnoreCase(ip) || LOCALHOST_IP.equalsIgnoreCase(ip)) {
                //根据网卡取本机配置的IP
                InetAddress iNet = null;
                try {
                    iNet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ip = iNet.getHostAddress();
            }
        }
        return ip;
    }
	
	 /**
     * 此方法调用百度AIP来查询IP所在国家
     * @param strIP（传入的IP地址）
     * @return
     */
    public static String getCountriesByIP(String strIP) {
        try {
            URL url = new URL("http://api.map.baidu.com/location/ip?ak=g3Rg2XVoPnbGPmfH9yAbxLlrfymi4h6S&ip="+strIP);
            URLConnection conn = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line = null;
            StringBuffer result = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            reader.close();
            String ipAddr = result.toString();
            try {
                JSONObject obj1= JSON.parseObject(ipAddr);
                if("0".equals(obj1.get("status").toString())){
                	String address = obj1.get("address").toString();
                    return address.split("\\|")[0];
                }else{
                    return null;
                }
            } catch (JSONException e) {
                e.printStackTrace();
                return null;
            }

        } catch (IOException e) {
        	return null;
        }
    }
	
    /**
     * 获取城市
     * @param strIP（传入的IP地址）
     * @return
     */
    public static String getCity(String strIP) {
        try {
            URL url = new URL("http://api.map.baidu.com/location/ip?ak=g3Rg2XVoPnbGPmfH9yAbxLlrfymi4h6S&ip="+strIP);
            URLConnection conn = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line = null;
            StringBuffer result = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            reader.close();
            String ipAddr = result.toString();
            try {
                JSONObject obj1= JSON.parseObject(ipAddr);
                if("0".equals(obj1.get("status").toString())){
                	String address = obj1.get("address").toString();
                	if(address.split("\\|").length > 3){
                		return address.split("\\|")[1]+","+address.split("\\|")[2];
                	}else{
                		return null;
                	}
                }else{
                    return null;
                }
            } catch (JSONException e) {
                e.printStackTrace();
                return null;
            }

        } catch (IOException e) {
        	return null;
        }
    }
    
    /**
     * 判断是否是国外ip
     * @param strIP
     * @return
     */
    public static boolean isForeignIp(String strIP) {
    	boolean flag = false;
    	String countries = getCountriesByIP(strIP);
    	if(countries != null && !countries.equals("CN")){
    		flag = true;
    	}
    	return flag;
    }
    
    public static void main(String[] args) {
		System.out.println(getCountriesByIP("119.123.243.53"));
		System.out.println(getCity("119.123.243.53"));
		System.out.println(isForeignIp("119.123.243.53"));
	}
    
}
